<template>
  <div class="finance-overview">
    <div class="page-container">
      <!-- 页面标题和日期筛选 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">财务概览统计</h1>
          <div class="date-filter">
            <a-range-picker
              v-model="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="onDateRangeChange"
              :allowClear="true"
              style="width: 240px; margin-right: 12px"
            />
            <a-button type="primary" @click="refreshData" :loading="loading">
              <a-icon type="reload" />
              刷新数据
            </a-button>
            <a-button @click="exportData" :loading="exportLoading">
              <a-icon type="download" />
              导出数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 概览数据卡片 -->
      <div class="data-cards-grid">
        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 统计期间内的总营业收入 </template>
            <div class="card-title">
              营业收入
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value" :class="getValueClass(overviewData.revenueGrowthRate)">
              ¥{{ formatNumber(overviewData.totalRevenue) }}
            </div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.revenueGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.revenueGrowthRate)" />
                {{ Math.abs(overviewData.revenueGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 统计期间内的总采购成本 </template>
            <div class="card-title">
              采购成本
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value" :class="getValueClass(-overviewData.costGrowthRate)">
              ¥{{ formatNumber(overviewData.totalCost) }}
            </div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.costGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.costGrowthRate)" />
                {{ Math.abs(overviewData.costGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 营业收入减去采购成本的毛利润 </template>
            <div class="card-title">
              毛利润
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value" :class="getValueClass(overviewData.profitGrowthRate)">
              ¥{{ formatNumber(overviewData.grossProfit) }}
            </div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.profitGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.profitGrowthRate)" />
                {{ Math.abs(overviewData.profitGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>

        <div class="data-card">
          <a-tooltip placement="top">
            <template slot="title"> 毛利润占营业收入的百分比 </template>
            <div class="card-title">
              毛利率
              <a-icon type="question-circle" style="color: #999; font-size: 12px; margin-left: 4px" />
            </div>
            <div class="card-value" :class="getValueClass(overviewData.marginGrowthRate)">
              {{ overviewData.profitMargin }}%
            </div>
            <div class="card-trend">
              <span class="trend-text">较上期</span>
              <span :class="getTrendClass(overviewData.marginGrowthRate)">
                <a-icon :type="getTrendIcon(overviewData.marginGrowthRate)" />
                {{ Math.abs(overviewData.marginGrowthRate) }}%
              </span>
            </div>
          </a-tooltip>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-grid">
        <!-- 收入成本对比图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">收入成本对比</h3>
            <div class="chart-controls">
              <a-select v-model="revenueChartPeriod" @change="updateRevenueChart" style="width: 120px">
                <a-select-option value="month">按月</a-select-option>
                <a-select-option value="quarter">按季度</a-select-option>
                <a-select-option value="year">按年</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="revenueChart" class="chart"></div>
          </div>
        </div>

        <!-- 利润率趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">利润率趋势</h3>
            <div class="chart-controls">
              <a-select v-model="profitChartPeriod" @change="updateProfitChart" style="width: 120px">
                <a-select-option value="month">按月</a-select-option>
                <a-select-option value="quarter">按季度</a-select-option>
                <a-select-option value="year">按年</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="profitChart" class="chart"></div>
          </div>
        </div>
      </div>

      <!-- 现金流量图 -->
      <div class="chart-card full-width">
        <div class="chart-header">
          <h3 class="chart-title">现金流量分析</h3>
          <div class="chart-controls">
            <a-select v-model="cashFlowPeriod" @change="updateCashFlowChart" style="width: 120px">
              <a-select-option value="month">按月</a-select-option>
              <a-select-option value="quarter">按季度</a-select-option>
            </a-select>
          </div>
        </div>
        <div class="chart-content">
          <div ref="cashFlowChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAction } from '@/api/manage'
import * as XLSX from 'xlsx'

export default {
  name: 'FinanceOverview',
  data() {
    return {
      loading: false,
      exportLoading: false,
      dateRange: [],
      revenueChartPeriod: 'month',
      profitChartPeriod: 'month',
      cashFlowPeriod: 'month',

      // 概览数据
      overviewData: {
        totalRevenue: 0,
        totalCost: 0,
        grossProfit: 0,
        profitMargin: 0,
        revenueGrowthRate: 0,
        costGrowthRate: 0,
        profitGrowthRate: 0,
        marginGrowthRate: 0,
      },

      // 图表实例
      charts: {
        revenue: null,
        profit: null,
        cashFlow: null,
      },

      // 图表数据
      chartData: {
        revenueComparison: [],
        profitTrend: [],
        cashFlow: [],
      },
    }
  },

  mounted() {
    this.initCharts()
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose()
      }
    })
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    initCharts() {
      this.$nextTick(() => {
        this.charts.revenue = echarts.init(this.$refs.revenueChart)
        this.charts.profit = echarts.init(this.$refs.profitChart)
        this.charts.cashFlow = echarts.init(this.$refs.cashFlowChart)
      })
    },

    onDateRangeChange() {
      this.refreshData()
    },

    handleResize() {
      Object.values(this.charts).forEach((chart) => {
        if (chart) {
          chart.resize()
        }
      })
    },

    async refreshData() {
      await this.loadData()
    },

    async loadData() {
      this.loading = true
      try {
        await Promise.all([this.loadOverviewData(), this.loadRevenueComparison(), this.loadProfitTrend(), this.loadCashFlow()])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    async loadOverviewData() {
      const params = this.getDateParams()
      const res = await getAction('/statistics/finance/overview', params)
      if (res.success && res.result) {
        this.overviewData = {
          totalRevenue: res.result.total_revenue || 0,
          totalCost: res.result.total_cost || 0,
          grossProfit: res.result.gross_profit || 0,
          profitMargin: res.result.gross_profit_rate || 0, // 使用grossProfitRate字段
          revenueGrowthRate: res.result.revenue_growth_rate || 0,
          costGrowthRate: res.result.cost_growth_rate || 0,
          profitGrowthRate: res.result.profit_growth_rate || 0,
          marginGrowthRate: res.result.margin_growth_rate || 0,
        }
      }
    },

    async loadRevenueComparison() {
      const params = {
        ...this.getDateParams(),
        period: this.revenueChartPeriod,
      }
      const res = await getAction('/statistics/finance/revenue-comparison', params)
      if (res.success && res.result) {
        this.chartData.revenueComparison = res.result
        this.updateRevenueChart()
      }
    },

    async loadProfitTrend() {
      const params = {
        ...this.getDateParams(),
        period: this.profitChartPeriod,
      }
      const res = await getAction('/statistics/finance/profit-trend', params)
      if (res.success && res.result) {
        this.chartData.profitTrend = res.result
        this.updateProfitChart()
      }
    },

    async loadCashFlow() {
      const params = {
        ...this.getDateParams(),
        period: this.cashFlowPeriod,
      }
      const res = await getAction('/statistics/finance/cash-flow', params)
      if (res.success && res.result) {
        this.chartData.cashFlow = res.result
        this.updateCashFlowChart()
      }
    },

    updateRevenueChart() {
      if (!this.charts.revenue) return

      const data = this.chartData.revenueComparison
      const periods = data.map((item) => item.period)
      const revenue = data.map((item) => item.revenue || 0)
      const cost = data.map((item) => item.cost || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['营业收入', '采购成本'],
        },
        xAxis: {
          type: 'category',
          data: periods,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => `¥${this.formatNumber(value)}`,
          },
        },
        series: [
          {
            name: '营业收入',
            type: 'bar',
            data: revenue,
            itemStyle: {
              color: '#1890ff',
            },
          },
          {
            name: '采购成本',
            type: 'bar',
            data: cost,
            itemStyle: {
              color: '#f5222d',
            },
          },
        ],
      }

      this.charts.revenue.setOption(option)
    },

    updateProfitChart() {
      if (!this.charts.profit) return

      const data = this.chartData.profitTrend
      const periods = data.map((item) => item.period)
      const profitMargin = data.map((item) => item.profit_margin || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}%`
          },
        },
        xAxis: {
          type: 'category',
          data: periods,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%',
          },
        },
        series: [
          {
            name: '毛利率',
            type: 'line',
            data: profitMargin,
            smooth: true,
            itemStyle: {
              color: '#52c41a',
            },
            lineStyle: {
              width: 3,
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(82, 196, 26, 0.3)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(82, 196, 26, 0.1)',
                  },
                ],
              },
            },
          },
        ],
      }

      this.charts.profit.setOption(option)
    },

    updateCashFlowChart() {
      if (!this.charts.cashFlow) return

      const data = this.chartData.cashFlow
      const periods = data.map((item) => item.period)
      const inflow = data.map((item) => item.inflow || 0)
      const outflow = data.map((item) => item.outflow || 0)
      const netFlow = data.map((item) => item.net_flow || 0)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: ['现金流入', '现金流出', '净现金流'],
        },
        xAxis: {
          type: 'category',
          data: periods,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => `¥${this.formatNumber(value)}`,
          },
        },
        series: [
          {
            name: '现金流入',
            type: 'bar',
            stack: 'flow',
            data: inflow,
            itemStyle: {
              color: '#52c41a',
            },
          },
          {
            name: '现金流出',
            type: 'bar',
            stack: 'flow',
            data: outflow.map((val) => -val),
            itemStyle: {
              color: '#f5222d',
            },
          },
          {
            name: '净现金流',
            type: 'line',
            data: netFlow,
            itemStyle: {
              color: '#1890ff',
            },
            lineStyle: {
              width: 3,
            },
          },
        ],
      }

      this.charts.cashFlow.setOption(option)
    },

    getDateParams() {
      const params = {}
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0].format('YYYY-MM-DD')
        params.endDate = this.dateRange[1].format('YYYY-MM-DD')
      }
      return params
    },

    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toLocaleString()
    },

    getValueClass(growthRate) {
      if (growthRate > 0) return 'value-positive'
      if (growthRate < 0) return 'value-negative'
      return ''
    },

    getTrendClass(growthRate) {
      if (growthRate > 0) return 'trend-positive'
      if (growthRate < 0) return 'trend-negative'
      return 'trend-neutral'
    },

    getTrendIcon(growthRate) {
      if (growthRate > 0) return 'arrow-up'
      if (growthRate < 0) return 'arrow-down'
      return 'minus'
    },

    async exportData() {
      this.exportLoading = true
      try {
        const params = this.getDateParams()

        // 导出所有统计数据
        const exportData = {
          概览数据: this.overviewData,
          收入成本对比: this.chartData.revenueComparison,
          利润率趋势: this.chartData.profitTrend,
          现金流量: this.chartData.cashFlow,
        }

        // 创建Excel数据
        const wb = XLSX.utils.book_new()

        // 概览数据工作表
        const overviewWs = XLSX.utils.json_to_sheet([this.overviewData])
        XLSX.utils.book_append_sheet(wb, overviewWs, '概览数据')

        // 收入成本对比工作表
        if (this.chartData.revenueComparison.length > 0) {
          const revenueWs = XLSX.utils.json_to_sheet(this.chartData.revenueComparison)
          XLSX.utils.book_append_sheet(wb, revenueWs, '收入成本对比')
        }

        // 利润率趋势工作表
        if (this.chartData.profitTrend.length > 0) {
          const profitWs = XLSX.utils.json_to_sheet(this.chartData.profitTrend)
          XLSX.utils.book_append_sheet(wb, profitWs, '利润率趋势')
        }

        // 现金流量工作表
        if (this.chartData.cashFlow.length > 0) {
          const cashFlowWs = XLSX.utils.json_to_sheet(this.chartData.cashFlow)
          XLSX.utils.book_append_sheet(wb, cashFlowWs, '现金流量')
        }

        // 生成文件名
        const fileName = `财务概览统计_${new Date().toISOString().slice(0, 10)}.xlsx`

        // 下载文件
        XLSX.writeFile(wb, fileName)

        this.$message.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.exportLoading = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.finance-overview {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 16px;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .date-filter {
      display: flex;
      align-items: center;
      gap: 12px;

      .ant-btn-primary {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 8px;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
      }

      .ant-btn:not(.ant-btn-primary) {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        color: #ffffff;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
          border-color: rgba(255, 255, 255, 0.4);
          color: #ffffff;
          transform: translateY(-1px);
        }
      }

      .ant-calendar-picker {
        .ant-calendar-picker-input {
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          backdrop-filter: blur(10px);

          &:hover {
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
      }
    }
  }
}

.data-cards-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.data-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;

  &.value-positive {
    color: #67c23a;
  }

  &.value-negative {
    color: #f56c6c;
  }
}

.card-trend {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;

  .trend-text {
    color: #909399;
  }

  .trend-positive {
    color: #67c23a;
  }

  .trend-negative {
    color: #f56c6c;
  }

  .trend-neutral {
    color: #909399;
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

.chart-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  &.full-width {
    grid-column: 1 / -1;
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-content {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

@media (max-width: 1200px) {
  .data-cards-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .data-cards-grid {
    grid-template-columns: 1fr;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
